package com.dizang.sharding.common.mapper;

import java.util.Iterator;
import java.util.Set;

import org.apache.ibatis.mapping.MappedStatement;

import tk.mybatis.mapper.annotation.LogicDelete;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

/**
 * 
 * @author kelvin
 * @date 2019-10-01
 * @param <T>
 */
public class UpdateListProvider extends MapperTemplate {

	public UpdateListProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
		super(mapperClass, mapperHelper);
	}

	/**
	 * 批量插入
	 *
	 * @param ms
	 */
	public String updateList(MappedStatement ms) {
		final Class<?> entityClass = getEntityClass(ms);
		// 开始拼sql
		StringBuilder sql = new StringBuilder();
		sql.append("<foreach collection=\"list\" item=\"record\" separator=\";\" >");
		Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
		sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass), "list[0]"));
		sql.append("<set>");
		for (EntityColumn column : columnList) {
			sql.append(column.getColumn() + "=");
			sql.append(column.getColumnHolder("record") + ",");
		}
		sql.append("</set>");

		sql.append("<where>");
		Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
		String buildMultiPkCaseCondition = buildMultiPkCondition(pkColumns);
        sql.append(buildMultiPkCaseCondition);
		sql.append("</where>");

		sql.append("</foreach>");
		return sql.toString();
	}
	
	String buildMultiPkCondition(Set<EntityColumn> pkColumns) {
        StringBuilder sql = new StringBuilder();
        // 为了兼容多个主键
        sql.append("(");
        for (Iterator<EntityColumn> iterator = pkColumns.iterator(); iterator.hasNext();) {
            EntityColumn entityColumn = (EntityColumn) iterator.next();
            sql.append(entityColumn.getColumn());
            if (iterator.hasNext()) {
                sql.append(",");
            }
        }
        sql.append(")");

        sql.append(" = ");

        
        // 每一组主键的值
        sql.append("(");
        for (Iterator<EntityColumn> iterator = pkColumns.iterator(); iterator.hasNext();) {
            EntityColumn entityColumn = (EntityColumn) iterator.next();
            sql.append(entityColumn.getColumnHolder("record"));
            if (iterator.hasNext()) {
                sql.append(",");
            }
        }
        sql.append(")");
        
        return sql.toString();
    }

}
